import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(const TomatoTimerApp());
  // 锁定竖屏
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
}

class TomatoTimerApp extends StatelessWidget {
  const TomatoTimerApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '番茄钟',
      theme: ThemeData(
        primarySwatch: Colors.red,
        scaffoldBackgroundColor: const Color(0xFFF5F5F5),
        textTheme: const TextTheme(
          displayLarge: TextStyle(fontSize: 72, fontWeight: FontWeight.bold, color: Colors.black87),
          titleLarge: TextStyle(fontSize: 24, fontWeight: FontWeight.w600, color: Colors.black87),
          bodyMedium: TextStyle(fontSize: 16, color: Colors.black54),
        ),
      ),
      darkTheme: ThemeData(
        primarySwatch: Colors.red,
        scaffoldBackgroundColor: const Color(0xFF1E1E1E),
        textTheme: const TextTheme(
          displayLarge: TextStyle(fontSize: 72, fontWeight: FontWeight.bold, color: Colors.white),
          titleLarge: TextStyle(fontSize: 24, fontWeight: FontWeight.w600, color: Colors.white),
          bodyMedium: TextStyle(fontSize: 16, color: Colors.white70),
        ),
      ),
      themeMode: ThemeMode.system,
      home: const TomatoTimerHome(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class TomatoTimerHome extends StatefulWidget {
  const TomatoTimerHome({super.key});

  @override
  State<TomatoTimerHome> createState() => _TomatoTimerHomeState();
}

class TimerMode {
  static const work = '工作';
  static const shortBreak = '短休息';
  static const longBreak = '长休息';
}

class _TomatoTimerHomeState extends State<TomatoTimerHome> with TickerProviderStateMixin {
  // 配置参数
  int workDuration = 25; // 工作时长（分钟）
  int shortBreakDuration = 5; // 短休息时长（分钟）
  int longBreakDuration = 15; // 长休息时长（分钟）
  int cyclesBeforeLongBreak = 4; // 几次工作后进入长休息

  // 状态变量
  String currentMode = TimerMode.work;
  int remainingSeconds = 25 * 60;
  bool isRunning = false;
  int completedCycles = 0;
  int completedWorks = 0;

  late AnimationController _controller;
  late Animation<double> _progressAnimation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: Duration(seconds: remainingSeconds),
    );

    _progressAnimation = Tween<double>(begin: 1.0, end: 0.0).animate(
      CurvedAnimation(parent: _controller, curve: Curves.linear),
    );

    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _handleTimerComplete();
      }
    });

    _controller.addListener(() {
      setState(() {
        remainingSeconds = (_controller.duration!.inSeconds * (1 - _controller.value)).round();
      });
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  // 处理计时器完成
  void _handleTimerComplete() {
    setState(() {
      isRunning = false;
      _controller.reset();

      if (currentMode == TimerMode.work) {
        completedWorks++;
        // 判断是否进入长休息
        if (completedWorks % cyclesBeforeLongBreak == 0) {
          currentMode = TimerMode.longBreak;
          remainingSeconds = longBreakDuration * 60;
        } else {
          currentMode = TimerMode.shortBreak;
          remainingSeconds = shortBreakDuration * 60;
        }
        _showNotification('休息时间到', '享受你的${currentMode}吧！');
      } else {
        // 休息结束，进入工作模式
        currentMode = TimerMode.work;
        remainingSeconds = workDuration * 60;
        if (currentMode == TimerMode.work && currentMode != TimerMode.shortBreak) {
          completedCycles++;
        }
        _showNotification('工作时间到', '开始专注工作吧！');
      }

      // 更新动画时长
      _controller.duration = Duration(seconds: remainingSeconds);
    });
  }

  // 显示通知
  void _showNotification(String title, String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(title, style: const TextStyle(fontWeight: FontWeight.bold)),
            Text(message),
          ],
        ),
        duration: const Duration(seconds: 3),
        behavior: SnackBarBehavior.floating,
      ),
    );

    // 播放系统提示音（需要导入 audioplayers 包，这里简化处理）
    SystemSound.play(SystemSoundType.alert);
  }

  // 格式化时间显示
  String _formatTime(int seconds) {
    final minutes = (seconds ~/ 60).toString().padLeft(2, '0');
    final secs = (seconds % 60).toString().padLeft(2, '0');
    return '$minutes:$secs';
  }

  // 切换计时器状态（开始/暂停）
  void _toggleTimer() {
    setState(() {
      isRunning = !isRunning;
      if (isRunning) {
        _controller.forward();
      } else {
        _controller.stop(canceled: false);
      }
    });
  }

  // 重置计时器
 void _resetTimer() {
  setState(() {
    isRunning = false;
    _controller.reset();
    currentMode = TimerMode.work;
    // 强制使用最新的 workDuration
    remainingSeconds = workDuration * 60;
    _controller.duration = Duration(seconds: remainingSeconds);
  });
}

  // 切换模式
  void _switchMode(String mode) {
  setState(() {
    currentMode = mode;
    isRunning = false;
    _controller.reset();

    // 切换时直接用最新配置的时长
    switch (mode) {
      case TimerMode.work:
        remainingSeconds = workDuration * 60;
        break;
      case TimerMode.shortBreak:
        remainingSeconds = shortBreakDuration * 60;
        break;
      case TimerMode.longBreak:
        remainingSeconds = longBreakDuration * 60;
        break;
    }

    _controller.duration = Duration(seconds: remainingSeconds);
  });
}

  // 打开设置页面
void _openSettings() async {
  final result = await Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => SettingsPage(
        workDuration: workDuration,
        shortBreakDuration: shortBreakDuration,
        longBreakDuration: longBreakDuration,
        cyclesBeforeLongBreak: cyclesBeforeLongBreak,
      ),
    ),
  );

  if (result != null && result is Map<String, int>) {
    // 1. 先保存新配置
    final newWorkDuration = result['workDuration']!;
    final newShortBreak = result['shortBreakDuration']!;
    final newLongBreak = result['longBreakDuration']!;
    final newCycles = result['cyclesBeforeLongBreak']!;

    setState(() {
      // 更新配置参数
      workDuration = newWorkDuration;
      shortBreakDuration = newShortBreak;
      longBreakDuration = newLongBreak;
      cyclesBeforeLongBreak = newCycles;

      // 2. 计算当前模式对应的新总时长（秒）
      int newTotalSeconds;
      if (currentMode == TimerMode.work) {
        newTotalSeconds = workDuration * 60;
      } else if (currentMode == TimerMode.shortBreak) {
        newTotalSeconds = shortBreakDuration * 60;
      } else {
        newTotalSeconds = longBreakDuration * 60;
      }

      // 3. 强制重置动画控制器（彻底同步状态）
      _controller.dispose(); // 销毁旧控制器
      // 重新初始化控制器
      _controller = AnimationController(
        vsync: this,
        duration: Duration(seconds: newTotalSeconds),
      );
      // 重新绑定动画监听
      _progressAnimation = Tween<double>(begin: 1.0, end: 0.0).animate(
        CurvedAnimation(parent: _controller, curve: Curves.linear),
      );
      _controller.addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          _handleTimerComplete();
        }
      });
      _controller.addListener(() {
        setState(() {
          remainingSeconds = (_controller.duration!.inSeconds * (1 - _controller.value)).round();
        });
      });

      // 4. 恢复运行状态（如果之前是运行中）
      remainingSeconds = newTotalSeconds; // 重置为新时长的初始值
      if (isRunning) {
        _controller.forward();
      }
    });
  }
}

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isDarkMode = theme.scaffoldBackgroundColor == const Color(0xFF1E1E1E);

    return Scaffold(
      appBar: AppBar(
        title: const Text('番茄钟'),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: _openSettings,
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(24.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // 模式选择器
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _ModeButton(
                  label: TimerMode.work,
                  isActive: currentMode == TimerMode.work,
                  onPressed: () => _switchMode(TimerMode.work),
                  color: Colors.red,
                ),
                const SizedBox(width: 16),
                _ModeButton(
                  label: TimerMode.shortBreak,
                  isActive: currentMode == TimerMode.shortBreak,
                  onPressed: () => _switchMode(TimerMode.shortBreak),
                  color: Colors.green,
                ),
                const SizedBox(width: 16),
                _ModeButton(
                  label: TimerMode.longBreak,
                  isActive: currentMode == TimerMode.longBreak,
                  onPressed: () => _switchMode(TimerMode.longBreak),
                  color: Colors.blue,
                ),
              ],
            ),
            const SizedBox(height: 24),
            // 进度圆环和时间显示
            Stack(
              alignment: Alignment.center,
              children: [
                // 背景圆环
                Container(
                  width: 280,
                  height: 280,
                  decoration: BoxDecoration(
                    color: isDarkMode ? const Color(0xFF2D2D2D) : Colors.white,
                    shape: BoxShape.circle,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black12,
                        blurRadius: 10,
                        offset: const Offset(0, 4),
                      ),
                    ],
                  ),
                ),
                // 进度圆环
                RotationTransition(
                  turns: const AlwaysStoppedAnimation(-90 / 360),
                  child: SizedBox(
                    width: 280,
                    height: 280,
                    child: CircularProgressIndicator(
                      value: _progressAnimation.value,
                      strokeWidth: 8,
                      backgroundColor: isDarkMode ? const Color(0xFF3D3D3D) : Colors.grey[200],
                      valueColor: AlwaysStoppedAnimation<Color>(
                        currentMode == TimerMode.work
                            ? Colors.red
                            : currentMode == TimerMode.shortBreak
                                ? Colors.green
                                : Colors.blue,
                      ),
                    ),
                  ),
                ),
                // 时间显示
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      _formatTime(remainingSeconds),
                      style: theme.textTheme.displayLarge,
                    ),
                    const SizedBox(height: 8),
                    Text(
                      currentMode == TimerMode.work ? '专注工作中' : '休息中',
                      style: theme.textTheme.bodyMedium,
                    ),
                  ],
                ),
              ],
            ),
            const SizedBox(height: 32),
            // 控制按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: _resetTimer,
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30),
                    ),
                    backgroundColor: isDarkMode ? const Color(0xFF3D3D3D) : Colors.grey[200],
                    foregroundColor: isDarkMode ? Colors.white : Colors.black87,
                  ),
                  child: const Text('重置', style: TextStyle(fontSize: 18)),
                ),
                const SizedBox(width: 24),
                ElevatedButton(
                  onPressed: _toggleTimer,
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30),
                    ),
                    backgroundColor: currentMode == TimerMode.work
                        ? Colors.red
                        : currentMode == TimerMode.shortBreak
                            ? Colors.green
                            : Colors.blue,
                    foregroundColor: Colors.white,
                  ),
                  child: Text(
                    isRunning ? '暂停' : '开始',
                    style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 24),
            // 统计信息
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _StatCard(
                  title: '已完成循环',
                  value: completedCycles.toString(),
                  icon: Icons.repeat,
                  color: Colors.orange,
                ),
                const SizedBox(width: 32),
                _StatCard(
                  title: '今日专注',
                  value: '${(completedWorks * workDuration / 60).toStringAsFixed(1)}h',
                  icon: Icons.timer,
                  color: Colors.red,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

// 模式选择按钮
class _ModeButton extends StatelessWidget {
  final String label;
  final bool isActive;
  final VoidCallback onPressed;
  final Color color;

  const _ModeButton({
    required this.label,
    required this.isActive,
    required this.onPressed,
    required this.color,
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return TextButton(
      onPressed: onPressed,
      style: TextButton.styleFrom(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
          side: BorderSide(color: isActive ? color : Colors.transparent),
        ),
        backgroundColor: isActive ? color.withOpacity(0.1) : Colors.transparent,
      ),
      child: Text(
        label,
        style: TextStyle(
          color: isActive ? color : theme.textTheme.bodyMedium?.color,
          fontSize: 16,
          fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
        ),
      ),
    );
  }
}

// 统计卡片
class _StatCard extends StatelessWidget {
  final String title;
  final String value;
  final IconData icon;
  final Color color;

  const _StatCard({
    required this.title,
    required this.value,
    required this.icon,
    required this.color,
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isDarkMode = theme.scaffoldBackgroundColor == const Color(0xFF1E1E1E);

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
      decoration: BoxDecoration(
        color: isDarkMode ? const Color(0xFF2D2D2D) : Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black12,
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          Icon(icon, color: color, size: 28),
          const SizedBox(height: 8),
          Text(title, style: theme.textTheme.bodyMedium),
          const SizedBox(height: 4),
          Text(
            value,
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: theme.textTheme.titleLarge?.color,
            ),
          ),
        ],
      ),
    );
  }
}

// 设置页面
class SettingsPage extends StatefulWidget {
  final int workDuration;
  final int shortBreakDuration;
  final int longBreakDuration;
  final int cyclesBeforeLongBreak;

  const SettingsPage({
    super.key,
    required this.workDuration,
    required this.shortBreakDuration,
    required this.longBreakDuration,
    required this.cyclesBeforeLongBreak,
  });

  @override
  State<SettingsPage> createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  late TextEditingController workController;
  late TextEditingController shortBreakController;
  late TextEditingController longBreakController;
  late TextEditingController cyclesController;

  @override
  void initState() {
    super.initState();
    workController = TextEditingController(text: widget.workDuration.toString());
    shortBreakController = TextEditingController(text: widget.shortBreakDuration.toString());
    longBreakController = TextEditingController(text: widget.longBreakDuration.toString());
    cyclesController = TextEditingController(text: widget.cyclesBeforeLongBreak.toString());
  }

  @override
  void dispose() {
    workController.dispose();
    shortBreakController.dispose();
    longBreakController.dispose();
    cyclesController.dispose();
    super.dispose();
  }

  // 验证输入是否为正整数
  bool _validateInput(String value) {
    if (value.isEmpty) return false;
    final int? num = int.tryParse(value);
    return num != null && num > 0;
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: const Text('设置'),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.pop(context),
        ),
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 8.0), // 调整右边距，避免贴边
            child: ElevatedButton(
              onPressed: () {
                if (_validateInput(workController.text) &&
                    _validateInput(shortBreakController.text) &&
                    _validateInput(longBreakController.text) &&
                    _validateInput(cyclesController.text)) {
                  Navigator.pop(context, {
                    'workDuration': int.parse(workController.text),
                    'shortBreakDuration': int.parse(shortBreakController.text),
                    'longBreakDuration': int.parse(longBreakController.text),
                    'cyclesBeforeLongBreak': int.parse(cyclesController.text),
                  });
                } else {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('请输入有效的正整数'),
                      backgroundColor: Colors.red,
                    ),
                  );
                }
              },
              // 按钮样式优化：红色背景、白色文字、圆角
              style: ElevatedButton.styleFrom(
                backgroundColor: Color.fromARGB(255, 182, 240, 193), 
                foregroundColor: Colors.white, // 文字白色
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8), // 圆角更美观
                ),
                // 去除默认阴影，适配 AppBar 风格
                elevation: 0,
              ),
              child: const Text(
                '保存',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600), // 加粗文字更突出
              ),
            ),
          ),
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.all(24.0),
        children: [
          _SettingItem(
            title: '工作时长（分钟）',
            controller: workController,
            hintText: '输入工作时长',
          ),
          const SizedBox(height: 20),
          _SettingItem(
            title: '短休息时长（分钟）',
            controller: shortBreakController,
            hintText: '输入短休息时长',
          ),
          const SizedBox(height: 20),
          _SettingItem(
            title: '长休息时长（分钟）',
            controller: longBreakController,
            hintText: '输入长休息时长',
          ),
          const SizedBox(height: 20),
          _SettingItem(
            title: '长休息前的循环次数',
            controller: cyclesController,
            hintText: '输入循环次数',
          ),
          const SizedBox(height: 24),
          const Text(
            '提示：\n'
            '- 工作时长建议设置为25分钟\n'
            '- 短休息建议5分钟，长休息建议15-30分钟\n'
            '- 每完成4个工作循环后建议进行一次长休息',
            style: TextStyle(color: Colors.grey, fontSize: 14),
          ),
        ],
      ),
    );
  }
}

// 设置项组件
class _SettingItem extends StatelessWidget {
  final String title;
  final TextEditingController controller;
  final String hintText;

  const _SettingItem({
    required this.title,
    required this.controller,
    required this.hintText,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
        ),
        const SizedBox(height: 8),
        TextField(
          controller: controller,
          keyboardType: TextInputType.number,
          decoration: InputDecoration(
            hintText: hintText,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
          ),
          inputFormatters: [
            FilteringTextInputFormatter.digitsOnly,
          ],
        ),
      ],
    );
  }
}